<template>
  <div class="video-tool">
    <div class="tool-header">
      <h3>🎬 音视频剪辑工具</h3>
      <p>支持视频剪切、格式转换、音频提取等功能</p>
      
      <!-- FFmpeg状态 -->
      <div class="ffmpeg-status" v-if="ffmpegInfo">
        <div v-if="ffmpegInfo.available" class="status-available">
          ✅ FFmpeg已就绪 - {{ ffmpegInfo.version }}
        </div>
        <div v-else class="status-unavailable">
          ❌ FFmpeg不可用 - {{ ffmpegInfo.message }}
        </div>
      </div>
    </div>

    <div class="video-sections">
      <!-- 文件选择区域 -->
      <div class="section">
        <h4>📁 选择文件</h4>
        <div class="file-input-area">
          <input 
            type="file" 
            ref="fileInput" 
            @change="handleFileSelect" 
            accept="video/*,audio/*"
            style="display: none"
          >
          <button @click="selectFile" class="select-btn">
            {{ selectedFile ? '重新选择文件' : '选择音视频文件' }}
          </button>
          <div v-if="selectedFile" class="file-info">
            <p><strong>文件名:</strong> {{ selectedFile.name }}</p>
            <p><strong>大小:</strong> {{ formatFileSize(selectedFile.size) }}</p>
            <p><strong>类型:</strong> {{ selectedFile.type }}</p>
          </div>
        </div>
      </div>

      <!-- 操作选择区域 -->
      <div class="section">
        <h4>⚙️ 选择操作</h4>
        <div class="operation-tabs">
          <button 
            v-for="op in operations" 
            :key="op.id"
            @click="currentOperation = op.id"
            :class="['tab-btn', { active: currentOperation === op.id }]"
          >
            {{ op.icon }} {{ op.name }}
          </button>
        </div>
      </div>

      <!-- 参数配置区域 -->
      <div class="section">
        <h4>🔧 参数配置</h4>
        
        <!-- 视频剪切 -->
        <div v-if="currentOperation === 'cut'" class="params">
          <div class="param-group">
            <label>开始时间 (秒):</label>
            <input v-model.number="params.startTime" type="number" min="0" step="0.1" placeholder="0">
          </div>
          <div class="param-group">
            <label>持续时间 (秒):</label>
            <input v-model.number="params.duration" type="number" min="0.1" step="0.1" placeholder="10">
          </div>
        </div>

        <!-- 音频剪切 -->
        <div v-if="currentOperation === 'audio_cut'" class="params">
          <div class="param-group">
            <label>开始时间 (秒):</label>
            <input v-model.number="params.startTime" type="number" min="0" step="0.1" placeholder="0">
          </div>
          <div class="param-group">
            <label>持续时间 (秒):</label>
            <input v-model.number="params.duration" type="number" min="0.1" step="0.1" placeholder="10">
          </div>
          <div class="param-group">
            <label>输出音频格式:</label>
            <select v-model="params.audioFormat">
              <option value="mp3">MP3</option>
              <option value="wav">WAV</option>
              <option value="aac">AAC</option>
              <option value="flac">FLAC</option>
              <option value="ogg">OGG</option>
            </select>
          </div>
          <div class="param-group">
            <label>音频质量:</label>
            <select v-model="params.audioBitrate">
              <option value="320k">320 kbps (高质量)</option>
              <option value="256k">256 kbps</option>
              <option value="192k">192 kbps (标准)</option>
              <option value="128k">128 kbps</option>
              <option value="96k">96 kbps (低质量)</option>
            </select>
          </div>
        </div>

        <!-- 格式转换 -->
        <div v-if="currentOperation === 'convert'" class="params">
          <div class="param-group">
            <label>输出格式:</label>
            <select v-model="params.outputFormat">
              <option value="mp4">MP4</option>
              <option value="avi">AVI</option>
              <option value="mov">MOV</option>
              <option value="mkv">MKV</option>
              <option value="webm">WebM</option>
            </select>
          </div>
          <div class="param-group">
            <label>视频质量:</label>
            <select v-model="params.quality">
              <option value="high">高质量</option>
              <option value="medium">中等质量</option>
              <option value="low">低质量</option>
            </select>
          </div>
        </div>

        <!-- 音频提取 -->
        <div v-if="currentOperation === 'extract'" class="params">
          <div class="param-group">
            <label>音频格式:</label>
            <select v-model="params.audioFormat">
              <option value="mp3">MP3</option>
              <option value="wav">WAV</option>
              <option value="aac">AAC</option>
              <option value="flac">FLAC</option>
            </select>
          </div>
          <div class="param-group">
            <label>音频质量:</label>
            <select v-model="params.audioBitrate">
              <option value="320k">320 kbps</option>
              <option value="256k">256 kbps</option>
              <option value="192k">192 kbps</option>
              <option value="128k">128 kbps</option>
            </select>
          </div>
        </div>

        <!-- 压缩 -->
        <div v-if="currentOperation === 'compress'" class="params">
          <div class="param-group">
            <label>压缩比例:</label>
            <select v-model="params.compressionRatio">
              <option value="0.8">轻度压缩 (80%)</option>
              <option value="0.6">中度压缩 (60%)</option>
              <option value="0.4">高度压缩 (40%)</option>
              <option value="0.2">极度压缩 (20%)</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 输出设置 -->
      <div class="section">
        <h4>📤 输出设置</h4>
        <div class="param-group">
          <label>输出文件名:</label>
          <input v-model="outputFileName" type="text" placeholder="自动生成">
        </div>
        <div class="param-group">
          <label>输出目录:</label>
          <div class="output-dir">
            <input v-model="outputDir" type="text" placeholder="选择输出目录" readonly>
            <button @click="selectOutputDir" class="dir-btn">选择目录</button>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="section">
        <div class="action-buttons">
          <button 
            @click="processVideo" 
            :disabled="!selectedFile || processing"
            class="process-btn"
          >
            {{ processing ? '处理中...' : '开始处理' }}
          </button>
          <button @click="clearAll" class="clear-btn">清空</button>
        </div>
      </div>

      <!-- 进度显示 -->
      <div v-if="processing || progress > 0" class="section">
        <h4>📊 处理进度</h4>
        <div class="progress-container">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progress + '%' }"></div>
          </div>
          <span class="progress-text">{{ progress.toFixed(1) }}%</span>
        </div>
        <div v-if="currentStatus" class="status-text">{{ currentStatus }}</div>
      </div>

      <!-- 结果显示 -->
      <div v-if="result" class="section">
        <h4>✅ 处理结果</h4>
        <div class="result-info">
          <p><strong>输出文件:</strong> {{ result.outputPath }}</p>
          <p><strong>处理时间:</strong> {{ result.processingTime }}秒</p>
          <p v-if="result.originalSize && result.outputSize">
            <strong>文件大小:</strong> 
            {{ formatFileSize(result.originalSize) }} → {{ formatFileSize(result.outputSize) }}
            ({{ ((result.outputSize / result.originalSize) * 100).toFixed(1) }}%)
          </p>
        </div>
        <div class="result-actions">
          <button @click="openOutputDir" class="open-btn">打开输出目录</button>
        </div>
      </div>

      <!-- 错误显示 -->
      <div v-if="error" class="section error-section">
        <h4>❌ 错误信息</h4>
        <div class="error-message">{{ error }}</div>
        <button @click="error = ''" class="clear-error-btn">清除错误</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ProcessVideo, GetFFmpegInfo } from '../../wailsjs/go/main/App'

// 响应式数据
const selectedFile = ref<(File & { path?: string }) | null>(null)
const currentOperation = ref('cut')
const processing = ref(false)
const progress = ref(0)
const currentStatus = ref('')
const result = ref<any>(null)
const error = ref('')
const outputDir = ref('')
const outputFileName = ref('')
const fileInput = ref<HTMLInputElement>()
const ffmpegInfo = ref<any>(null)

// 操作类型
const operations = [
  { id: 'cut', name: '视频剪切', icon: '✂️' },
  { id: 'audio_cut', name: '音频剪切', icon: '🎵✂️' },
  { id: 'convert', name: '格式转换', icon: '🔄' },
  { id: 'extract', name: '音频提取', icon: '🎵' },
  { id: 'compress', name: '视频压缩', icon: '📦' }
]

// 参数配置
const params = ref({
  // 剪切参数
  startTime: 0,
  duration: 10,
  // 转换参数
  outputFormat: 'mp4',
  quality: 'medium',
  // 音频提取参数
  audioFormat: 'mp3',
  audioBitrate: '192k',
  // 压缩参数
  compressionRatio: 0.6
})

// 文件选择
function selectFile() {
  fileInput.value?.click()
}

function handleFileSelect(event: Event) {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    // 创建一个包含文件路径信息的对象
    selectedFile.value = {
      ...file,
      path: (file as any).path || file.name // 在Electron/Wails环境中可能有path属性
    }
    // 自动生成输出文件名
    generateOutputFileName()
  }
}

// 生成输出文件名
function generateOutputFileName() {
  if (!selectedFile.value) return
  
  const baseName = selectedFile.value.name.replace(/\.[^/.]+$/, '')
  const operation = operations.find(op => op.id === currentOperation.value)
  
  let suffix = ''
  switch (currentOperation.value) {
    case 'cut':
      suffix = '_cut'
      break
    case 'audio_cut':
      suffix = `_audio_cut.${params.value.audioFormat}`
      break
    case 'convert':
      suffix = `_converted.${params.value.outputFormat}`
      break
    case 'extract':
      suffix = `_audio.${params.value.audioFormat}`
      break
    case 'compress':
      suffix = '_compressed'
      break
  }
  
  outputFileName.value = baseName + suffix
}

// 选择输出目录
function selectOutputDir() {
  // 这里需要调用Go后端的目录选择功能
  // 暂时使用默认目录
  outputDir.value = 'C:\\Users\\Public\\Videos\\MyTools_Output'
}

// 处理视频
async function processVideo() {
  if (!selectedFile.value) {
    error.value = '请先选择文件'
    return
  }
  
  processing.value = true
  progress.value = 0
  result.value = null
  error.value = ''
  
  try {
    // 构建请求参数
    const request = {
      inputFile: selectedFile.value?.path || selectedFile.value?.name || '',
      outputFile: `${outputDir.value || 'output'}/${outputFileName.value}`,
      operation: currentOperation.value,
      startTime: String(params.value.startTime || ''),
      duration: String(params.value.duration || ''),
      format: params.value.outputFormat || '',
      quality: String(params.value.quality || ''),
      audioFormat: params.value.audioFormat || '',
      audioBitrate: params.value.audioBitrate || ''
    }
    
    currentStatus.value = '正在处理...'
    
    // 调用Go后端的FFmpeg处理功能
    const processResult = await ProcessVideo(request)
    
    if (processResult.success) {
      progress.value = 100
      currentStatus.value = '处理完成'
      
      result.value = {
        outputPath: request.outputFile,
        processingTime: 0, // FFmpeg输出中可以解析实际时间
        originalSize: selectedFile.value?.size || 0,
        outputSize: 0 // 可以通过文件系统API获取输出文件大小
      }
    } else {
      throw new Error(processResult.message)
    }
    
    processing.value = false
    
  } catch (err) {
    error.value = `处理失败: ${err}`
    processing.value = false
  }
}

// 清空所有
function clearAll() {
  selectedFile.value = null
  result.value = null
  error.value = ''
  progress.value = 0
  currentStatus.value = ''
  outputFileName.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 打开输出目录
function openOutputDir() {
  // 调用Go后端打开文件夹
  // window.go.main.App.OpenDirectory(outputDir.value)
}

// 初始化
onMounted(async () => {
  try {
    ffmpegInfo.value = await GetFFmpegInfo()
  } catch (err) {
    console.warn('FFmpeg信息获取失败:', err)
  }
})

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.video-tool {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 30px;
}

.tool-header h3 {
  color: #fff;
  font-size: 1.8em;
  margin: 0 0 10px 0;
}

.tool-header p {
  color: #ccc;
  margin: 0;
}

.video-sections {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.section h4 {
  color: #fff;
  margin: 0 0 15px 0;
  font-size: 1.2em;
}

.file-input-area {
  text-align: center;
}

.select-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: transform 0.2s;
}

.select-btn:hover {
  transform: translateY(-2px);
}

.file-info {
  margin-top: 15px;
  text-align: left;
  background: rgba(0, 0, 0, 0.3);
  padding: 15px;
  border-radius: 8px;
}

.file-info p {
  color: #fff;
  margin: 5px 0;
}

.operation-tabs {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.tab-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 10px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.tab-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: transparent;
}

.params {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.param-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.param-group label {
  color: #fff;
  font-weight: 500;
}

.param-group input,
.param-group select {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
}

.param-group input:focus,
.param-group select:focus {
  outline: none;
  border-color: #667eea;
}

.output-dir {
  display: flex;
  gap: 10px;
}

.output-dir input {
  flex: 1;
}

.dir-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.dir-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.process-btn {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s;
}

.process-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(17, 153, 142, 0.4);
}

.process-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.clear-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #11998e 0%, #38ef7d 100%);
  transition: width 0.3s ease;
}

.progress-text {
  color: #fff;
  font-weight: 600;
  min-width: 50px;
}

.status-text {
  color: #ccc;
  margin-top: 10px;
  font-style: italic;
}

.result-info p {
  color: #fff;
  margin: 8px 0;
}

.result-actions {
  margin-top: 15px;
}

.open-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.2s;
}

.open-btn:hover {
  transform: translateY(-2px);
}

.error-section {
  border-color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
}

.error-message {
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 10px;
}

.clear-error-btn {
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .operation-tabs {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .progress-container {
    flex-direction: column;
    gap: 10px;
  }
  
  .output-dir {
    flex-direction: column;
  }
}
.ffmpeg-status {
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.status-available {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-unavailable {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
</style>